export default {
	// 开启命名空间
	namespaced: true,
	state: () => ({
		// 项目初识化从本地存储当中quchu
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	/* 
	 state中的数据只能通过mutations中的方法修改
	 */
	mutations: {
		/* 
		 修改购物车的商品的数量
		 */
		addToCart(state, goods) {
			const findObj = state.cart.find(item => item.goods_id === goods.goods_id)
			if (!findObj) {
				state.cart.push(goods)
			} else {
				findObj.goods_count++
			}
			this.commit('m_cart/saveToStorage')
		},
		/* 
		 持久化数据保存,存储到本地
		 */
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		/* 
		 更新购物车中商品的状态
		 */
		updateGoodsStatus(state, goods) {
			const findObj = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findObj) {
				findObj.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		/* 
		 更新购物车中商品的数量
		 */
		updateGoodsNum(state, goods) {
			const findObj = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findObj) {
				findObj.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		/* 
		 删除购物车的商品
		 */
		deleteGoodsShop(state, goods) {
			// const findObj = state.cart.find(item => item.goods_id === goods.goods_id)
			// if (findObj) {
			// 	state.cart.splice(findObj, 1)
			// 	this.commit('m_cart/saveToStorage')
			// 	console.log(state.cart, '数据');
			// }
			state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		/* 
		 修改购物车中所有商品的状态
		 */
		updateAllGoodsState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
	},
	getters: {
		/* 
		 计算购物车的商品的总数量
		 */
		total(state) {
			// let c = 0
			// state.cart.forEach(item => c += item.goods_count)
			// return c
			return state.cart.reduce((total, item) => total += item.goods_count, 0)
		},
		/* 
		 计算勾选商品的数量
		 */
		checkCount(state) {
			return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		/* 
		 计算所有勾选状态的总价格
		 */
		checkedAllSum(state) {
			// 先过滤出来选中状态的商品,然后计算这些选中状态的商品价格
			return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum + item.goods_count * item
				.goods_price, 0).toFixed(
				2)
		},
	}
}